<template>
  <div class="music-ball" v-if="visible">
    <audio ref="audio" :src="musicUrl" @ended="onMusicEnd"></audio>
    <div class="controls">
      <button style="font-weight: bold;font-size: 15px" @click="togglePlay">{{ isPlaying ? "暂停" : "播放" }}</button>
      <span style="font-size: 12px">{{ musicName }}</span>
    </div>
  </div>
</template>

<script setup>
import {ref, watch} from "vue";

const props = defineProps({
  musicUrl: String,
  musicName: String,
});

const visible = ref(true)
const isPlaying = ref(false)

const audio = ref(null)

const togglePlay = () => {
  if (!audio.value) return
  if (isPlaying.value) {
    audio.value.pause()
  } else {
    audio.value.play()
  }
  isPlaying.value = !isPlaying.value
};

const onMusicEnd = () => {
  isPlaying.value = false
}

// 监听 URL 改变并重置状态
watch(() => props.musicUrl, (newUrl) => {
  if (audio.value) {
    audio.value.pause()
    audio.value.load()
    isPlaying.value = false
  }
})
</script>

<style scoped>
.music-ball {
  position: fixed;
  bottom: 10%;
  right: 20px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 10px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  z-index: 999;
}
.controls {
  display: flex;
  flex-direction: column;
  align-items: center;
}
button {
  background: none;
  border: none;
  color: #fff;
  cursor: pointer;
}
</style>
